import {DirectiveOptions} from "vue/types/options";
import {Message} from "element-ui";
import {ClipboardUtils, MYel} from "../../utils/clipboardUtils";

export const ClickCopy: DirectiveOptions = {
  inserted(el: MYel, binding) {
    el.__copyText__ = (e: MouseEvent) => {
      if (ClipboardUtils.isSupported()) {
        ClipboardUtils.copyText(el, binding.value, e).then(() => {
          Message.success('已复制到剪切板')
        }).catch(() => {
          Message.error('复制失败')
        })
      } else {
        Message.error('当前浏览器不支持复制功能')
      }
    }
    el.addEventListener('click', el.__copyText__)
  },
  componentUpdated(el: MYel, binding) {
    ClickCopy.unbind(el, binding)
    ClickCopy.inserted(el, binding)
  },
  unbind(el: MYel, binding) {
    el.removeEventListener('click', el.__copyText__)
  }
}
